<template>
  <el-card class="box-card">
    <!-- 卡片顶部添加品牌按钮 -->
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">添加品牌</el-button>
    <!-- 表格组件，用于展示已有的数据 -->
    <!--
      table
      ---border:是否有纵向的边框
      table-column
      ---lable：某一个列表
      ---width：设置这一列的宽度
      ---align：设置这一列对齐方式
     -->
    <el-table style="margin: 10px 0px" border :data="trademarkArr">
      <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
          prop="index"
      ></el-table-column>
      <el-table-column label="品牌名称" prop="tmName"></el-table-column>
      <el-table-column label="品牌LOGO">
        <template #default="{row}">
          <div class="demo-image__preview">
            <el-image
                style="width: 100px; height: 100px"
                :src="row.logoUrl"
                :preview-src-list="[row.logoUrl]"
                :initial-index="0"
                :preview-teleported="true"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #default="{row}">
          <el-button type="primary" size="mini" icon="Edit" @click="updateTrademark(row)">编辑</el-button>
          <el-popconfirm :title="`您确定要删除${row.tmName}?`" @confirm="removeTradeMark(row.id)" width="250px"
                         icon="Delete">
            <template #reference>
              <el-button type="danger" size="mini" icon="Delete" @click="deleteTrademark(row)">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器组件 -->
    <!--
      pagination
      ---v-model:current-page：设置当前分页器页码
      ---v-model:page-size:设置每一也展示数据条数
      ---page-sizes：每页显示个数选择器的选项设置
      ---background:背景颜色
      ---layout：分页器6个子组件布局的调整 "->"把后面的子组件顶到右侧
     -->
    <el-pagination
        @size-change="sizeChange"
        @current-change="changePageNo"
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[5, 20, 30, 50]"
        :background="true"
        layout=" prev, pager, next, jumper,->,total, sizes,"
        :total="total"
    />
  </el-card>
  <!-- 添加品牌弹出框 -->
  <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'">
    <el-form style="width: 80%" :model="trademarkParams" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
        <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
        >
          <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl" class="avatar"/>

          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <!--    具名插槽：footer-->
    <template #footer>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
      <el-button type="primary" size="default" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
//引入组合式API函数
import {nextTick, onMounted, reactive, ref} from 'vue'
import {reqAddOrUpdateTrademark, reqHasTrademark, reqDeleteTrademark} from "@/api/product/trademark";
import type {Records, TradeMark} from "@/api/product/trademark/type.ts";
import {ElMessage} from "element-plus";

onMounted(() => {
  //获取已有品牌数据
  getHasTrademark()
})
//当前页码
let pageNo = ref<number>(1)
//每一页展示的数据
let limit = ref<number>(5)
//存储已有品牌数据总数
let total = ref<number>(0)
//存储已有品牌数据
let trademarkArr = ref<Records>([])
let dialogFormVisible = ref<boolean>(false)
//定义新增品牌数据
let trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: ''
})
//获取表单组件实例
let formRef = ref<any>(null)

//获取已有品牌数据函数
const getHasTrademark = async (pager = 1) => {
  //调用获取已有品牌数据接口
  pageNo.value = pager
  let res = await reqHasTrademark(pageNo.value, limit.value)
  if (res.code === 200) {
    //获取已有品牌数据总数
    total.value = res.data.total
    //获取已有品牌数据
    trademarkArr.value = res.data.records
  }
}

//跳转页码
const changePageNo = (newPageNo: number) => {
  getHasTrademark(newPageNo)
}
//每页展示数据条数
const sizeChange = (newLimit: number) => {
  limit.value = newLimit
  getHasTrademark()
}
//删除
const deleteTrademark = (row: any) => {
  console.log(row)
}

//添加品牌
const addTrademark = () => {
  dialogFormVisible.value = true
  trademarkParams.id = 0
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  //清除表单校验结果
  formRef.value?.clearValidate('tmName')
  formRef.value?.clearValidate('logoUrl')
}
//修改品牌
const updateTrademark = (row: any) => {
  //清空表单校验结果
  nextTick(() => {
    formRef.value.clearValidate('tmName')
    formRef.value.clearValidate('logoUrl')
  })
  //修改品牌弹出框
  dialogFormVisible.value = true
  //ES6语法合并对象
  Object.assign(trademarkParams, row)
}
//弹窗取消按钮
const cancel = () => {
  dialogFormVisible.value = false
}
//弹窗确定按钮
const confirm = async () => {
  //在发请求之前，对整个表单进行校验 await作用只有校验通过才会执行后面的代码
  await formRef.value.validate();
  let result: any = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code === 200) {
    //关闭对话框
    dialogFormVisible.value = false
    //弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功'
    })
    await getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    //添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败'
    })
    //关闭对话框
    dialogFormVisible.value = false
  }
}

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  if (
      rawFile.type == 'image/png' ||
      rawFile.type == 'image/jpeg' ||
      rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小不能超过4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}
//图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (response: any, uploadFile: any) => {
  //response:即为当前这次上传图片post请求服务器返回的数据
  //收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}


//表单校验规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
const validatorLogoUrl = (rule: any, value: any, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('品牌LOGO不能为空'))
  }
}

//表单校验规则对象
const rules = {
  tmName: [
    {required: true, trigger: 'blur', validator: validatorTmName},
    {min: 2, max: 10, message: '品牌名称长度在2到10个字符', trigger: 'blur'}
  ],
  logoUrl: [
    {required: true, trigger: 'blur', validator: validatorLogoUrl}
  ]
}
//气泡确认框确定按钮的回调
const removeTradeMark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功'
    })
    //再次获取已有的品牌数据
    await getHasTrademark(
        trademarkArr.value.length === 1 && pageNo.value > 1 ? pageNo.value - 1 : pageNo.value
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败'
    })
  }
}
</script>
<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
